import { Directive, DirectiveBinding } from 'vue'

const vResize: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    /* 
    min为最小宽度/高度
    hoverColor悬浮颜色
    lineColor线的颜色，用于复选后恢复线的初始颜色
    showHoverColor是否鼠标光标悬浮就展示颜色，默认拖拽过程中才改变颜色
    direction 拖拽的方向，horizontal/vertical，默认值horizontal水平
    */
    const min = binding.value?.min || 20
    const hoverColor = binding.value?.hoverColor || '#88f'
    const lineColor = binding.value?.lineColor || '#ccc'
    const showHoverColor = binding.value?.showHoverColor || false
    const direction = binding.value?.direction || 'horizontal'
    if (showHoverColor && hoverColor) {
      el.onpointerenter = () => {
        el.style.backgroundColor = hoverColor
      }
      el.onpointerleave = () => {
        el.style.backgroundColor = lineColor
      }
    }
    el.onpointerdown = (e: PointerEvent) => {
      e.preventDefault() // 阻止选中
      let leftDom = el.previousElementSibling as HTMLElement
      let rightDom = el.nextElementSibling as HTMLElement
      const { width: leftDOMWidth, height: leftDOMHeight, left: leftDOMLeft, top: leftDOMTop } = leftDom.getBoundingClientRect()
      const { width: rightDOMWidth, height: rightDOMHeight } = rightDom.getBoundingClientRect()
      let moveRange = direction === 'horizontal' ? (leftDOMWidth + rightDOMWidth) : (leftDOMHeight + rightDOMHeight)
      let shiftX = e.clientX - el.getBoundingClientRect().left
      let shiftY = e.clientY - el.getBoundingClientRect().top
      el.setPointerCapture(e.pointerId)
      if (!showHoverColor) {
        el.style.backgroundColor = hoverColor
      }
      const pointerMove = (e: PointerEvent) => {
        if (direction === 'horizontal') {
          // 水平方向
          let moveX = e.clientX - shiftX - leftDOMLeft
          if (moveX < min) {
            moveX = min
          }
          if (moveX > moveRange - min) {
            moveX = moveRange - min
          }
          el.style.left = moveX + 'px'
          leftDom.style.width = moveX + 'px'
          rightDom.style.width = moveRange - moveX + 'px'
        } else {
          // 垂直方向
          let moveY = e.clientY - shiftY - leftDOMTop
          if (moveY < min) {
            moveY = min
          }
          if (moveY > moveRange - min) {
            moveY = moveRange - min
          }
          el.style.top = moveY + 'px'
          leftDom.style.height = moveY + 'px'
          rightDom.style.height = moveRange - moveY + 'px'
        }
      }
      el.onpointermove = pointerMove
      el.onpointerup = () => {
        if (!showHoverColor) {
          el.style.backgroundColor = lineColor
        }
        el.onpointerup = null
        el.onpointermove = null
      }

    }
  }
}

export default vResize